import { computed, ref, watch } from "vue";
import gsap from "gsap";
const colors = ["#334552", "#B34335", "#6E9FA5", "#A2C3AC", "#C8846C"];
export default function useGdp(gdpRef, maxSize) {
  const maxValue = computed(() => {
    if (gdpRef.value.length) {
      return Math.max(...gdpRef.value.map((it) => it.value));
    }
    return 0;
  });

  const bars = ref([]);

  //最终状态
  const barsTarget = computed(() => {
    return gdpRef.value.map((it, i) => ({
      ...it,
      size: (it.value / maxValue.value) * 400,
      color: colors[i % colors.length],
    }));
  });

  watch(
    barsTarget,
    () => {
      //将bars从当前状态变成barsTargset
      for (let i = 0; i < barsTarget.value.length; i++) {
        //初始化
        if (!bars.value[i]) {
          bars.value[i] = {
            ...barsTarget.value[i],
            size: 0,
            value: 0,
          };
        }
        //逐渐变化
        gsap.to(bars.value[i], {
          ...barsTarget.value[i],
          duration: 1,
        });
      }
    },
    { deep: true }
  );

  return {
    bars,
  };
}
